package com.bxd.baodan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.AskInfoItem;
import com.bxd.baodan.item.GroupBean;
import com.bxd.baodan.item.QesTagBean;
import com.bxd.baodan.item.SortItem;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.MyTextWatcher;

import java.util.ArrayList;
import java.util.List;

/**
 * 想买保险,有疑问
 */
public class AskServiceActivity extends BaseActivity {
    List<SortItem> tagList = new ArrayList<>();
    List<SortItem> tag27List = new ArrayList<>();

    public TextView companyTv;
    ListView lv;

    MAdapter adapter;

    List<GroupBean> list = new ArrayList<>();

    String currentAge, insure_type, question_type, currentGender, otherQuestion, company;
    public String tid;


    CommonAdapter insureTypeAdapter;  //预算
    CommonAdapter questionTypeAdapter;
    private AskInfoItem askInfoItem;
    AskInfoItem.KeyBuyInsure keyBuyInsure;
    AskInfoItem.Doubt doubt;
    private String qid;
    private String company_id;
    boolean isFinish;
    private String question_content ="";
    private boolean isFinishError;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask);
        setActionBarTitle("已买保险,有疑问");
        askInfoItem = new AskInfoItem();
        keyBuyInsure = new AskInfoItem.KeyBuyInsure();
        doubt = new AskInfoItem.Doubt();
        askInfoItem.choice = 1 + "";
        askInfoItem.type = 0 + "";


        findViewById(R.id.bar_iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExitDialog("确认退出快速提问吗?");
            }
        });

        lv = (ListView) findViewById(R.id.lv);

        initAdapter();


        NetUtil netUtil = new NetUtil(this, JsonApi.QUESTION_OPTIONS);
        netUtil.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {

                QesTagBean qesTagBean = new Gson().fromJson(result, QesTagBean.class);
                List<SortItem> tag = qesTagBean.data.list.tag;
                List<SortItem> tag27 = qesTagBean.data.list.tag27;
                tagList.clear();
                tag27List.clear();
                if (tag != null) {
                    tagList.addAll(tag);
                    insureTypeAdapter.notifyDataSetChanged();
                }

                if (tag27 != null) {
                    tag27List.addAll(tag27);
                    tid = tag27List.get(0).tid;
                    questionTypeAdapter.notifyDataSetChanged();
                }
            }
        });


        GroupBean first = new GroupBean();
        first.middleVisible = true;
        first.layout = R.layout.ask_question_type;
        list.add(first);


        adapter = new MAdapter(this, list);

        adapter.setListener(new OkListener() {
            @Override
            public void next(int position, GroupBean nextBean) {

                GroupBean current = list.get(position);
                if (position == 0) {
                    current.leftVisible = false;
                    current.rightVisible = false;
                } else {
                    current.leftVisible = true;
                    current.rightVisible = true;
                }

                current.middleVisible = false;

                nextBean.leftVisible = true;
                nextBean.rightVisible = true;
                nextBean.middleVisible = true;


                list.add(nextBean);
                adapter.notifyDataSetChanged();
                lv.smoothScrollToPosition(adapter.getCount());

            }


            @Override
            public void pre(int position) {
                list.get(position - 1).middleVisible = true;
                list.remove(position);
                adapter.notifyDataSetChanged();
                lv.setSelection(adapter.getCount());
            }
        });
        lv.setAdapter(adapter);
    }

    private void initAdapter() {
        insureTypeAdapter = new CommonAdapter<SortItem>(AskServiceActivity.this, tagList, R.layout.ask_check_item_noclick) {
            @Override
            public void convert(final ViewHolder holder, final SortItem item) {
                final CheckBox checkBox = (CheckBox) holder.getView(R.id.check);
                LinearLayout check_ly = (LinearLayout) holder.getView(R.id.check_ly);

                checkBox.setText(item.name);
                checkBox.setChecked(item.isChecked);


                check_ly.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean check = !item.isChecked;
                        for (int i = 0; i < tagList.size(); i++) {
                            if (i == holder.getPosition()) {
                                tagList.get(i).isChecked = check;
                                if (check) {
                                    insure_type = tagList.get(i).name;
                                    keyBuyInsure.insureType = item.id;  // TODO: 2017/11/14 保险类型
                                } else {
                                    insure_type = "";
                                }
                            } else {
                                tagList.get(i).isChecked = false;
                            }

                        }
                        insureTypeAdapter.notifyDataSetChanged();

                    }
                });


            }
        };
        questionTypeAdapter = new CommonAdapter<SortItem>(AskServiceActivity.this, tag27List, R.layout.ask_check_item_noclick) {
            @Override
            public void convert(final ViewHolder holder, final SortItem item) {
                final CheckBox checkBox = (CheckBox) holder.getView(R.id.check);
                LinearLayout check_ly = (LinearLayout) holder.getView(R.id.check_ly);

                checkBox.setText(item.name);
                checkBox.setChecked(item.isChecked);


                check_ly.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean check = !item.isChecked;
                        for (int i = 0; i < tag27List.size(); i++) {
                            if (i == holder.getPosition()) {
                                tag27List.get(i).isChecked = check;
                                if (check) {
                                    question_type = tag27List.get(i).name;
                                    doubt.doubt = item.id;  // TODO: 2017/11/14 预算
                                } else {
                                    question_type = "";
                                }
                            } else {
                                tag27List.get(i).isChecked = false;
                            }

                        }
                        questionTypeAdapter.notifyDataSetChanged();

                    }
                });


            }
        };
    }


    class MAdapter extends BaseAdapter {
        private List<GroupBean> list;
        private Context context;
        private OkListener listener;


        MAdapter(Context context, List<GroupBean> list) {
            this.list = list;
            this.context = context;
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {

            final ViewHolder holder;
            final GroupBean item = list.get(i);
            if (view == null) {
                view = View.inflate(AskServiceActivity.this, R.layout.ask_list_item, null);
                holder = new ViewHolder();
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.left = (TextView) view.findViewById(R.id.left);
            holder.right = (TextView) view.findViewById(R.id.right);
            holder.middle = (LinearLayout) view.findViewById(R.id.middle);


            holder.left.setVisibility(item.leftVisible ? View.VISIBLE : View.GONE);
            holder.right.setVisibility(item.rightVisible ? View.VISIBLE : View.GONE);
            holder.middle.setVisibility(item.middleVisible ? View.VISIBLE : View.GONE);


            holder.left.setText(item.left);
            holder.right.setText(item.right);
            ViewGroup mid = (ViewGroup) View.inflate(context, item.layout, null);


            holder.middle.removeAllViews();
            holder.middle.addView(mid);

            if (item.middleVisible) {


                try {
                    mid.findViewById(R.id.finish).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }


                switch (item.layout) {
                    case R.layout.ask_question_type:
                        parseQuestionType(mid);
                        break;

                    case R.layout.ask_item_company:
                        parseCompany(mid);

                        break;

                    case R.layout.ask_insure_type_buy:
                        parseInsureType(mid);
                        break;

                    case R.layout.ask_item_other_question:
                        parseOtherQuestion(mid);
                        break;
                    case R.layout.ask_item_finish:
                        parseFinish(mid);
                        break;

                }


                mid.findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {


                        GroupBean nextBean = new GroupBean();

                        switch (item.layout) {


                            case R.layout.ask_question_type:
                                if (StringUtil.isEmpty(question_type)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                nextBean.left = "您咨询的问题类型";
                                nextBean.layout = R.layout.ask_item_company;
                                nextBean.right = question_type;
                                break;


                            case R.layout.ask_item_company:
                                if (StringUtil.isEmpty(company)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                nextBean.left = "您买了哪家保险公司的产品";
                                nextBean.layout = R.layout.ask_insure_type_buy;
                                nextBean.right = company;
                                break;


                            case R.layout.ask_insure_type_buy:
                                if (StringUtil.isEmpty(insure_type)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                nextBean.left = "您购买的保险类型";
                                nextBean.layout = R.layout.ask_item_other_question;
                                nextBean.right = insure_type;
                                break;

                            case R.layout.ask_item_other_question:
                                if (StringUtil.isEmpty(otherQuestion)) {
                                    showToast("请完善信息");
                                    return;
                                }
                                if (otherQuestion.length() < 5) {
                                    showToast("字数这么少，真的把想问的说清楚了吗？");
                                    return;
                                }
                                nextBean.left = "补充说明";
                                nextBean.right = otherQuestion;
                                nextBean.layout = R.layout.ask_item_finish;

                                break;

                        }


                        listener.next(i, nextBean);
                    }
                });

                try {
                    mid.findViewById(R.id.bar_iv_close).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            listener.pre(i);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return view;
        }

        public void setListener(OkListener listener) {
            this.listener = listener;
        }

        class ViewHolder {
            TextView left;
            TextView right;
            LinearLayout middle;
        }


    }

    private void parseFinish(final ViewGroup mid) {
        final TextView et = (TextView) mid.findViewById(R.id.content);
        et.setText(question_content);
        mid.findViewById(R.id.open_question).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getInstance().finishOtherActivity(MainActivity.class);
             //   openActivity(AllQuestionActivity.class);
                openActivity(QuestionDetailActivity.class, new String[]{"qid"}, new String[]{qid});
                finish();
            }
        });
        if (isFinishError) {
            mid.setVisibility(View.GONE);
        }
        if (!(isFinish||isFinishError)) {

            NetUtil netUtil = new NetUtil(AskServiceActivity.this, JsonApi.QUESTION_ADDQUESTION);
            askInfoItem.keyOfBuyInsure = keyBuyInsure;
            askInfoItem.doubt = doubt;

            final String json = new Gson().toJson(askInfoItem);

            LogUtil.e("想买保险提问json: " + json);

            netUtil.setParams("options", json);
            netUtil.setParams("cateId", tid);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    String data = JSONUtil.getData(result);
                    question_content = JSONUtil.getData("content", data);
                    et.setText(question_content);
                    qid = JSONUtil.getData("qid", data);
                    isFinish = true;

                }

                @Override
                public void onError(String result) {
                    if (JSONUtil.getCode(result) == 8000) {
                        //token过期
                        LoginInfo.getInstance(App.getContext()).cancelLogin(App.getContext());
                        App.getContext().sendBroadcast(new Intent(Constant.ACTION_LOGIN_LOGINOUT));
                    }
                    Toast.makeText(App.getContext(), JSONUtil.getMessage(result), Toast.LENGTH_LONG).show();
                    mid.setVisibility(View.GONE);
                    isFinishError = true;
                }
            });
        }

    }

    private void parseOtherQuestion(ViewGroup mid) {
        final EditText et = (EditText) mid.findViewById(R.id.et_question);
        et.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                otherQuestion = et.getText().toString();
                askInfoItem.supplement = otherQuestion;  // TODO: 2017/11/14 补充说明
            }
        });
    }

    private void parseCompany(ViewGroup mid) {
        currentGender = "";

        LinearLayout ly = (LinearLayout) mid.findViewById(R.id.company_ly);
        companyTv = (TextView) mid.findViewById(R.id.company_tv);
        ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivityForResult(AllCompanyActivity.class, new String[]{"company_name"}, new String[]{""});
            }
        });

    }

    private void parseQuestionType(ViewGroup mid) {
        // TODO: 2017/11/13 单选 保险类型
        mid.findViewById(R.id.bar_iv_close).setVisibility(View.GONE);
        question_type = "";
        for (SortItem item :
                tag27List) {
            item.isChecked = false;
        }

        GridView gv = (GridView) mid.findViewById(R.id.type_gv);

        gv.setAdapter(questionTypeAdapter);
    }

    private void parseInsureType(ViewGroup mid) {
        // TODO: 2017/11/13 单选 保险类型
        insure_type = "";
        for (SortItem item :
                tagList) {
            item.isChecked = false;
        }

        GridView gv = (GridView) mid.findViewById(R.id.type_gv);

        gv.setAdapter(insureTypeAdapter);


    }


    interface OkListener {
        public void next(int position, GroupBean bean);

        public void pre(int position);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            showExitDialog("确认退出快速提问吗?");
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
            company = data.getStringExtra("company_name");
            company_id = data.getStringExtra("company_id");
            companyTv.setText(company);
            keyBuyInsure.company = company_id;
        }
    }

}
